package com.bluemartini.jmx.callback;

import com.bluemartini.dna.BMException;
import com.bluemartini.dna.BMLog;
import com.bluemartini.dna.Callback;
import com.bluemartini.dna.DNAList;
import com.bluemartini.dna.DNAListIterator;
import com.bluemartini.jmx.BMMBeanServer;
import com.bluemartini.jmx.mbean.Cache;
import com.bluemartini.util.HTMLVersionUtil;

/**
 * Register as MBean the cache list returned by HTMLVersionUtil.getCacheStats(). <br/>
 * Add this class to the heart beat callback section to refresh
 * regularly the registered MBean list.
 * 
 * @author Yannick Robin
 *
 */
public class CacheMBeanRegister implements Callback {

	public DNAList execute(DNAList dnaIn) throws BMException
	{
		registerCacheMBeans();
		return null;
	}
	
	private void registerCacheMBeans() throws BMException
	{
		BMLog.log(BMLog.COMPONENT_SYSTEM, 1, "[CacheMBeanRegisterCallback.registerCacheMBeans] Refresh Blue Martini Cache MBeans");
		
		DNAList dnaCacheStats = HTMLVersionUtil.getCacheStats();
		DNAListIterator iter = dnaCacheStats.alphaIterator();
		
		String name;
		while ((name = iter.nextName()) != null)
		{		
			Cache mbean = new Cache(name);
	        //semicolon is not support for Object Name
	        name = name.replace(':', '_');		        
	        BMMBeanServer.registerMBean(BMMBeanServer.MBEAN_DOMAIN_NAME + ":Name=" + name + ",Type=Cache", mbean);
		}
	}
	
}
